// 预览
export const preview = (url, data) => {
  const imgUrl = url.indexOf('https') > -1 ? url.replace('https', 'http') : url
  let dataList
  if (data) {
    dataList = data.map(val => val.indexOf('https') > -1 ? val.replace('https', 'http') : val)
  }
  wx.previewImage({
    current: imgUrl,
    urls: data ? dataList : [imgUrl]
  })
}

// 视频or图片
export const fileType = (data) => {
  return ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'jpeg'].indexOf(data.split('.')[data.split('.').length - 1]) > -1 ? 'image' : 'video'
}

// 下载权限
export const writePhotosAlbumStatus = (data) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              resolve(true)
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '请授权保存到相册',
                showCancel: false,
                success (res1) {
                  if (res1.confirm) {
                    wx.openSetting({
                      success () {
                      }
                    })
                  }
                }
              })
            }
          })
        } else {
          resolve(true)
        }
      }
    })
  })
}

// 保存文件
export const saveFileList = (data) => {
  return new Promise((resolve, reject) => {
    writePhotosAlbumStatus().then(res => {
      if (res) {
        wx.showLoading({
          title: '正在保存',
          mask: true
        })
        let index = 0
        data.map(val => {
          downloadFileImg(val).then(res1 => {
            if (fileType(res1) === 'image') {
              wx.saveImageToPhotosAlbum({
                filePath: res1,
                complete(res) {
                  index++
                }
              })
            } else {
              
              wx.saveVideoToPhotosAlbum({
                filePath: res1,
                complete (res) {
                  // console.log(res, '视频')
                  index++
                }
              })
            }
          })
        })
        // 定时器
        const downloadStatus = setInterval(_=>{
          if (index >= data.length) {
            clearInterval(downloadStatus)
            wx.hideLoading()
            resolve(true)
            wx.showToast({
              icon: 'none',
              title: '保存成功'
            })
          }
        }, 500)
      }
    })
  })
}

// 图片转本地
export const downloadFileImg = (data) => {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: data.indexOf('https://') > -1 ? data : data.replace('http://', 'https://'),
      success(res) {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath)
        }
      }
    })
  })
}

